<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogFormVisible"
    width="500px"
    @close="close"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-form-item :hidden="isDoAdd" label="id" prop="id">
        <el-input
          v-model="form.id"
          autocomplete="off"
          :disabled="!isDoAdd"
        ></el-input>
      </el-form-item>
      <el-form-item label="名称" prop="displayName">
        <el-input v-model="form.displayName" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input v-model="form.sort" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="form.remark"
          autocomplete="off"
          type="textarea"
          :autosize="{ minRows: 3 }"
        ></el-input>
      </el-form-item>
      <el-form-item label="禁用" prop="disabled">
        <el-checkbox v-model="form.disabled"></el-checkbox>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="save">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { doEdit, doAdd } from '@/api/departmentManagement'

  export default {
    name: 'ManagementEdit',
    props: {
      idKey: {
        type: String,
        default: function () {
          return 'id'
        },
      },
    },
    data() {
      return {
        form: {
          id: '',
          sort: 1,
        },
        rules: {
          displayName: [{ required: true, trigger: 'blur', message: '请输入' }],
        },
        title: '',
        dialogFormVisible: false,
        isDoAdd: false,
      }
    },
    created() {},
    methods: {
      showEdit(row) {
        if (!row[this.idKey]) {
          this.title = '添加'
          this.isDoAdd = true
        } else {
          this.title = '编辑'
          this.isDoAdd = false

          this.form = Object.assign({}, row)
        }
        this.dialogFormVisible = true
      },
      close() {
        this.$refs['form'].resetFields()
        this.form = this.$options.data().form
        this.dialogFormVisible = false
      },
      save() {
        this.$refs['form'].validate(async (valid) => {
          if (valid) {
            let _msg = ''
            if (this.isDoAdd) {
              const { msg } = await doAdd(this.form)
              _msg = msg
            } else {
              const { msg } = await doEdit(this.form)
              _msg = msg
            }
            this.$baseMessage(_msg, 'success')
            this.$emit('fetch-data')
            this.close()
          } else {
            return false
          }
        })
      },
    },
  }
</script>
